package com.personal.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.personal.book.commons.AjaxResponse;
import com.personal.book.entity.Users;
import com.personal.book.service.impl.UserServiceImpl;
import com.personal.tools.MD5Utils;
import com.personal.tools.PageData;

/**
 * UserServlet1
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Users user = new Users();
	UserServiceImpl usi = new UserServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 编码
		request.setCharacterEncoding("utf-8");
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		// 登录
		if ("login".equals(op)) {
			doLogin(request, response);
		}
		// 注册
		else if ("register".equals(op)) {
			doRegister(request, response);
		}
		// 验证注册的用户名是否重名
		else if ("ajaxusername".equals(op)) {
			doajaxusername(request, response);
		}
		// 用戶模糊分頁查詢
		else if ("queryByPage".equals(op)) {
			// 分页有关的查询 数据处理 页面跳转等
			doQueryByPage(request, response);
		}
		// 刪除用户
		else if ("del".equals(op)) {
			doDel(request, response);
		}
		// 修改用户前在页面默认显示用户信息
		else if ("updateInfo".equals(op)) {
			doUpdateInfo(request, response);
		}
		// 修改用户信息
		else if ("update".equals(op)) {
			doUpdate(request, response);
		}
		// 重置修改页面的用户信息
		else if ("reset".equals(op)) {
			doReset(request, response);
		}
		// 修改页面的用户信息
		else if ("userMessage".equals(op)) {
			doUpdateMessage(request, response);
		}
		// 管理员修改用户信息
		else if ("adminupdateuser".equals(op)) {
			AdminUpdateUser(request, response);
		}
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doRegister(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = request.getParameter("username");
		String userPwd = request.getParameter("userpwd");
		String idCard = request.getParameter("idcard");
		String tel = request.getParameter("tel");
		String addr = request.getParameter("addr");
		Users user = new Users(0, userName, userPwd, idCard, tel, addr);
		boolean flag = usi.Add(user);
		if (flag) {
			request.getSession().setAttribute("userName", userName);
			request.getRequestDispatcher("login.jsp").forward(request, response);
		} else {
			request.setAttribute("msg", "注册失败！请重新注册。");
			request.getRequestDispatcher("login.jsp").forward(request, response);

		}
	}

	/**
	 * 验证用户名是否重名
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doajaxusername(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String userName = request.getParameter("username");
		System.out.println("username :" + response);
		// 2 调用 service的方法,查询是否存在username对象
		Users user = usi.getUserByName(userName);
		// 我们以后再进行ajax请求的时候，我们希望返回结果是一个标准的格式
		// AjaxResponse: ->msg status data 等等
		// 目前可以简单处理，直接返回一个字符串
		String msg = "exists";
		if (user == null) {
			// ?没有找到
			msg = "notexists";
		}
		AjaxResponse ajaxResponse = new AjaxResponse(msg, 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(ajaxResponse);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * 登录.
	 */
	private void doLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String userName = request.getParameter("username");
		String userPwd = MD5Utils.getEncodeByMd5(request.getParameter("password"));
		// 2 调用 service的方法,查询是否存在typename对象
		boolean flag = usi.Login(userName, userPwd);
		System.out.println(flag);
		if (flag) {
			request.getSession().setAttribute("userName", userName);
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} else {
			request.setAttribute("msg", "登录失败!请重新登录!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

	/**
	 * 模糊查询 分页
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认值为1
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 2;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}

		// 3 调用 Service的方法
		PageData<Users> pd = usi.getUsersByKeyword(page, pageSize, keywords);

		// 4传递PageData对象给jsp，此时传递的是pageData的对象
		request.setAttribute("pd", pd);

		// 4.-1转发回来的时候，我们将查询关键字也存储在request范围内
		request.setAttribute("keywords", keywords);

		// 5 转发
		request.getRequestDispatcher("userInfo.jsp").forward(request, response);
	}

	/**
	 * 删除用户
	 */
	private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		int delId = Integer.parseInt(request.getParameter("userId"));
		// 2 调用 service的方法,删除用户
		boolean flag = usi.Del(delId);
		System.out.println(flag);
		if (flag) {

			request.getRequestDispatcher("userInfo.jsp").forward(request, response);
		} else {
			request.setAttribute("msg", "删除失败!");
			request.getRequestDispatcher("userInfo.jsp").forward(request, response);
		}
	}

	/**
	 * 管理员 修改页面默认显示要修改的用户信息
	 */
	private void doUpdateInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String userName = request.getParameter("userName");

		// 2 调用 service的方法,返回对应userName的用户信息
		Users user = usi.getUserByName(userName);
		// 将对应编辑的用户信息传到修改页面默认显示
		request.setAttribute("user", user);
		// 转发到userUpdate.jsp
		request.getRequestDispatcher("userUpdate.jsp").forward(request, response);
	}

	/**
	 * 管理员 修改用户信息
	 */
	private void AdminUpdateUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		//获取数据
		Integer userId = Integer.parseInt(request.getParameter("userid"));
		String userName = request.getParameter("username");
		String userPwd = request.getParameter("userpwd");
		String idCard = request.getParameter("idcard");
		String tel = request.getParameter("tel");
		String addr = request.getParameter("addr");

		Users users = new Users(userId, userName, userPwd, idCard, tel, addr);
		// 2 调用 service的方法,修改用户信息
		boolean flag = usi.Update(users);
		System.out.println(flag);
		//根据结果操作
		if (flag) {
			request.getRequestDispatcher("userInfo.jsp").forward(request, response);
		} else {
			request.setAttribute("msg", "修改失败!");
			request.getRequestDispatcher("userUpdate.jsp").forward(request, response);

		}
	}

	/**
	 * 用户查询个人信息 修改页面默认显示要修改的用户信息
	 */
	private void doUpdateMessage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		//获取用户名
		String userName = (String) request.getSession().getAttribute("userName");
		// 2 调用 service的方法,返回对应userName的用户信息
		Users user = usi.getUserByName(userName);
		// 将对应编辑的用户信息传到修改页面默认显示
		request.getSession().setAttribute("user", user);
		System.out.println(userName);
		// 转发到userUpdate.jsp
		request.getRequestDispatcher("userMessage.jsp").forward(request, response);
	}

	/**
	 * 用户修改自己个人信息 获取信息，修改用户
	 */
	private void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		//获取数据
		Integer userId = Integer.parseInt(request.getParameter("userId"));
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		String idCard = request.getParameter("idCard");
		String tel = request.getParameter("tel");
		String addr = request.getParameter("addr");

		Users users = new Users(userId, userName, userPwd, idCard, tel, addr);

		// 2 调用 service的方法,修改用户信息
		boolean flag = usi.Update(users);
		System.out.println(flag);
		//根据结果做相关操作
		if (flag) {
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} else {
			request.setAttribute("msg", "修改失败!");
			request.getRequestDispatcher("userMessage.jsp").forward(request, response);

		}
	}

	/**
	 * 重置修改页面的用户信息
	 */
	private void doReset(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2.将用户信息以null赋值
		boolean flag = usi.Update(new Users(null, null, null, null, null));

		if (flag) {
			request.getRequestDispatcher("userInfo.jsp").forward(request, response);
		} else {
			request.setAttribute("msg1", "重置失败!");
			request.getRequestDispatcher("userUpdate.jsp").forward(request, response);

		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
